package com.android.manghe.orderpay.presenter;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.android.base.frame.presenter.XPresenter;
import com.android.base.okhttp.okUtil.OKHttpUtil;
import com.android.base.okhttp.okUtil.base.NetBean;
import com.android.base.okhttp.okUtil.callback.GsonBaseBack;
import com.android.base.tools.ToastUtil;
import com.android.manghe.cache.StatusHolder;
import com.android.manghe.cache.UserHolder;
import com.android.manghe.common.model.AliPayRes;
import com.android.manghe.common.model.BaseBack;
import com.android.manghe.common.model.BuyGoodShangMengZhiFuRes;
import com.android.manghe.common.model.PaymentTypeRes;
import com.android.manghe.common.model.SimpleResult;
import com.android.manghe.common.model.WXPayRes;
import com.android.manghe.common.model.WechatConfig;
import com.android.manghe.common.model.YiZhiFuRes;
import com.android.manghe.config.ConstantsUrl;
import com.android.manghe.market.model.CartGoodListRes;
import com.android.manghe.mine.model.AddressInfo;
import com.android.manghe.mine.model.MemberIndexRes;
import com.android.manghe.orderpay.activity.MarketOrderPayFromCartActivity;
import com.android.manghe.orderpay.model.MarketSubmitOrderRes;
import com.android.manghe.utils.ApiCrypter;
import com.android.manghe.utils.PayResult;
import com.bestpay.app.PaymentTask;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class PMarketOrderPayFromCart extends XPresenter<MarketOrderPayFromCartActivity> {

    public List<CartGoodListRes.DataBean.CartGoodsBean> selectedGoodList;
    public boolean isMember;
    public AddressInfo currentAddress;
    public PaymentTypeRes.DataBean.PaymentBean selectedPayBean;

    public void setCurrentAddress(AddressInfo currentAddress) {
        this.currentAddress = currentAddress;
    }

    public void setPayType(PaymentTypeRes.DataBean.PaymentBean selectedPayBean) {
        this.selectedPayBean = selectedPayBean;
    }

    public void loadAddressList() {
        HashMap<String, String> data = new HashMap<>();
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(getV()));
        headMap.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
headMap.put("PLATFORM", "android");
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.MEMBERADDRESSLIST, data, headMap)
                .get()
                .execute(new GsonBaseBack<AddressInfo>() {

                    @Override
                    public void onSuccess(Call call, AddressInfo addressInfo) {
                        if (addressInfo != null && addressInfo.code == 0 && addressInfo.data != null && !addressInfo.data.isEmpty()) {
                            for (AddressInfo addr : addressInfo.data) {
                                if (TextUtils.equals(addr.is_default, "1")) {
                                    getV().showAddress(addr);
                                    return;
                                }
                            }
                            getV().showAddress(addressInfo.data.get(0));
                        } else {
                            getV().showAddress(null);
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                        getV().showAddress(null);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void getPaymentType() {
        HashMap<String, String> data = new HashMap<>();
        new OKHttpUtil(getV()).url(ConstantsUrl.domain + ConstantsUrl.FLOWPAYMENT, data)
                .get()
                .execute(new BaseBack<PaymentTypeRes>() {

                    @Override
                    public void onSuccess(Call call, PaymentTypeRes res) {
                        if (res != null && res.data != null && res.data.payment != null && res.data.payment.size() != 0) {
                            getV().updatePayments(res.data.payment);
                            selectedPayBean = res.data.payment.get(0);
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                    }

                    @Override
                    public void onComplete() {
                        getV().hideLoadingDialog();
                    }
                });
    }

    public boolean isPayByIntegral() {
        for (CartGoodListRes.DataBean.CartGoodsBean good : selectedGoodList) {
            if (good.goods_price != 0) {
                return false;
            }
        }
        return true;
    }

    public void toPay(String mark, int couponPrice) {
        if (selectedPayBean == null) {
            return;
        }
        StatusHolder.mCurrentPayType = 2;
        getV().showLoadingDialog();
        HashMap<String, String> data = new HashMap<>();
        data.put("address_id", currentAddress.id);
        data.put("ajax", "1");
        data.put("order_tip", mark);
        data.put("is_exempt", "0");
//        data.put("coupon_favourable_price", couponPrice + "");
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(getV()));
        headMap.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
headMap.put("PLATFORM", "android");
        headMap.put("PLATFORM", "android");
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.DIRECTBUY_SUBMITORDER, headMap)
                .post(data).build()
                .execute(new BaseBack<MarketSubmitOrderRes>() {
                    @Override
                    public void onSuccess(Call call, MarketSubmitOrderRes res) {
                        if (res != null) {
                            if (res.code == 0) {
                                if (res.data != null) {
                                    HashMap<String, String> data = new HashMap<>();
                                    data.put("order_sn", res.data.order_sn + "");
                                    data.put("pay_id", selectedPayBean.pay_id + "");

                                    if (isPayByIntegral()) {
                                        //只用积分付款
                                        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.DIRECTBUY_TOPAY, headMap)
                                                .post(data)
                                                .build()
                                                .execute(new BaseBack<NetBean>() {
                                                    @Override
                                                    public void onSuccess(Call call, NetBean netBean) {
                                                        getV().hideLoadingDialog();
                                                        if (netBean != null) {
                                                            if (netBean.code == 100008) {
                                                                getV().paySuccess();
                                                            } else {
                                                                getV().hideLoadingDialog();
                                                                getV().payFail();
                                                            }
                                                        } else {
                                                            getV().hideLoadingDialog();
                                                            getV().payFail();
                                                        }
                                                    }

                                                    @Override
                                                    public void onFailure(Exception e) {
                                                        super.onFailure(e);
                                                        getV().hideLoadingDialog();
                                                        getV().payFail();
                                                    }

                                                    @Override
                                                    public void onComplete() {
                                                        getV().hideLoadingDialog();
                                                    }
                                                });
                                    }else if(selectedPayBean.pay_code.equals("shangmeng")){
                                        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.DIRECTBUY_TOPAY, headMap)
                                                .post(data).build()
                                                .execute(new BaseBack<BuyGoodShangMengZhiFuRes>() {
                                                    @Override
                                                    public void onSuccess(Call call, BuyGoodShangMengZhiFuRes res) {
                                                        getV().hideLoadingDialog();
                                                        if (res != null && res.data != null) {
                                                            getV().openQuickPay(res.data);
                                                        } else {
                                                            getV().payFail();
                                                        }
                                                    }

                                                    @Override
                                                    public void onFailure(Exception e) {
                                                        super.onFailure(e);
                                                        getV().hideLoadingDialog();
                                                        getV().payFail();
                                                    }

                                                    @Override
                                                    public void onComplete() {
                                                        getV().hideLoadingDialog();
                                                    }
                                                });
                                    }else if(selectedPayBean.pay_code.equals("yizfpay")){
                                        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.DIRECTBUY_TOPAY, headMap)
                                                .post(data).build()
                                                .execute(new BaseBack<YiZhiFuRes>() {
                                                    @Override
                                                    public void onSuccess(Call call, YiZhiFuRes res) {
                                                        getV().hideLoadingDialog();
                                                        if (res != null && res.data != null && res.data.paycode != null) {
                                                            toPayYiZhiFu(new GsonBuilder().disableHtmlEscaping().create().toJson(res.data.paycode));
                                                        } else {
                                                            getV().payFail();
                                                        }
                                                    }

                                                    @Override
                                                    public void onFailure(Exception e) {
                                                        super.onFailure(e);
                                                        getV().hideLoadingDialog();
                                                        getV().payFail();
                                                    }

                                                    @Override
                                                    public void onComplete() {
                                                        getV().hideLoadingDialog();
                                                    }
                                                });
                                    } else if (selectedPayBean.pay_code.equals("alipayapp")) {
                                        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.DIRECTBUY_TOPAY, headMap)
                                                .post(data).build()
                                                .execute(new BaseBack<AliPayRes>() {

                                                    @Override
                                                    public void onSuccess(Call call, AliPayRes res) {
                                                        getV().hideLoadingDialog();
                                                        if (res != null && res.data != null && res.data.paycode != null) {
                                                            toPayByAli(res.data.paycode);
                                                        } else {
                                                            getV().payFail();
                                                        }
                                                    }

                                                    @Override
                                                    public void onFailure(Exception e) {
                                                        super.onFailure(e);
                                                        getV().hideLoadingDialog();
                                                        getV().payFail();
                                                    }

                                                    @Override
                                                    public void onComplete() {
                                                        getV().hideLoadingDialog();
                                                    }
                                                });
                                    } else if (selectedPayBean.pay_code.equals("wxpayapp") || selectedPayBean.pay_code.equals("wxpayapp2")) {
                                        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.DIRECTBUY_TOPAY, headMap)
                                                .post(data).build()
                                                .execute(new BaseBack<WXPayRes>() {

                                                    @Override
                                                    public void onSuccess(Call call, WXPayRes res) {
                                                        getV().hideLoadingDialog();
                                                        if (res != null && res.data != null && res.data.paycode != null && res.data.paycode.appid != null) {
                                                            new OKHttpUtil(getV()).url(ConstantsUrl.domain + (selectedPayBean.pay_code.equals("wxpayapp") ? ConstantsUrl.WX_CONFIG : ConstantsUrl.WX_CONFIG2))
                                                                    .get()
                                                                    .execute(new GsonBaseBack() {
                                                                        @Override
                                                                        public void onSuccess(Call call, String json) {
                                                                            getV().hideLoadingDialog();
                                                                            NetBean<String> netBean = new Gson().fromJson(json, NetBean.class);
                                                                            if (netBean != null && netBean.code == 0 && !TextUtils.isEmpty(netBean.data)) {
                                                                                try {
                                                                                    String dataString = URLDecoder.decode(new String(new ApiCrypter().decrypt(netBean.data), "UTF-8"), "UTF-8");
                                                                                    if (!TextUtils.isEmpty(dataString)) {
                                                                                        WechatConfig config = new Gson().fromJson(dataString, WechatConfig.class);
                                                                                        if (config != null) {
                                                                                            if (!TextUtils.isEmpty(config.wxpay_app_id)) {
                                                                                                ConstantsUrl.PAY_WX_APPID = config.wxpay_app_id;
                                                                                            }
                                                                                            toPayByWx(res.data.paycode);
                                                                                        } else {
                                                                                            getV().payFail();
                                                                                        }
                                                                                    }
                                                                                } catch (Exception e) {
                                                                                    e.printStackTrace();
                                                                                    getV().payFail();
                                                                                }
                                                                            }
                                                                        }

                                                                        @Override
                                                                        public void onFailure(Exception e) {
                                                                            super.onFailure(e);
                                                                            getV().hideLoadingDialog();
                                                                            getV().payFail();
                                                                        }

                                                                        @Override
                                                                        public void onComplete() {

                                                                        }
                                                                    });
                                                        } else {
                                                            getV().payFail();
                                                        }
                                                    }

                                                    @Override
                                                    public void onFailure(Exception e) {
                                                        super.onFailure(e);
                                                        getV().hideLoadingDialog();
                                                        getV().payFail();
                                                    }

                                                    @Override
                                                    public void onComplete() {
                                                    }
                                                });
                                    } else {
                                        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.DIRECTBUY_TOPAY, headMap)
                                                .post(data).build()
                                                .execute(new BaseBack<AliPayRes>() {

                                                    @Override
                                                    public void onSuccess(Call call, AliPayRes res) {
                                                        getV().hideLoadingDialog();
                                                        if (res != null && res.data != null && res.data.paycode != null) {
                                                            if(selectedPayBean.pay_code.equals("yipayweixinh5")){
                                                                //微信H5，打开手机浏览器
                                                                getV().toPayByBrowser(res.data.paycode, res.data.log_id);
                                                            } else {
                                                                //其他就打开浏览器支付。例如盛付通
                                                                getV().toPayByH5(res.data.paycode);
                                                            }
                                                        } else {
                                                            getV().payFail();
                                                        }
                                                    }

                                                    @Override
                                                    public void onFailure(Exception e) {
                                                        super.onFailure(e);
                                                        getV().hideLoadingDialog();
                                                        getV().payFail();
                                                    }

                                                    @Override
                                                    public void onComplete() {
                                                        getV().hideLoadingDialog();
                                                    }
                                                });
                                    }
                                } else {
                                    ToastUtil.showLong(getV(), "请求支付失败");
                                }
                            } else {
                                ToastUtil.showLong(getV(), res.msg);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                    }

                    @Override
                    public void onComplete() {
                        getV().hideLoadingDialog();
                    }
                });
    }


    private static final int SDK_PAY_FLAG = 1;
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {
//                        ToastUtil.showShort(getV(), "支付成功");
                        getV().paySuccess();
                    } else {
                        if (TextUtils.equals(resultStatus, "8000") || TextUtils.equals(resultStatus, "6004")) {
                            ToastUtil.showShort(getV(), "支付结果确认中");
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            ToastUtil.showShort(getV(), "支付取消");
                        } else if (TextUtils.equals(resultStatus, "6002")) {
                            ToastUtil.showShort(getV(), "网络异常");
                        } else if (TextUtils.equals(resultStatus, "5000")) {
                            ToastUtil.showShort(getV(), "重复请求");
                        } else {
                            // 其他值就可以判断为支付失败
                            ToastUtil.showShort(getV(), "支付失败");
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    private void toPayByAli(String orderInfo) {

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(getV());
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void toPayByWx(WXPayRes.DataBean.PaycodeBean bean) {
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(getV(), ConstantsUrl.PAY_WX_APPID, true);
        iwxapi.registerApp(ConstantsUrl.PAY_WX_APPID);
        PayReq req = new PayReq();
        req.appId = ConstantsUrl.PAY_WX_APPID;
        req.partnerId = bean.partnerid;
        req.prepayId = bean.prepayid;
        req.packageValue = bean.wxpackage;
        req.nonceStr = bean.noncestr;
        req.timeStamp = bean.timestamp + "";
        req.sign = bean.sign;
        iwxapi.sendReq(req);
    }
    public void checkOrderStatus(String orderId){
        getV().showLoadingDialog();
        new OKHttpUtil(getV()).url(ConstantsUrl.domain + String.format(ConstantsUrl.IsOrderPayed, orderId))
                .get()
                .execute(new GsonBaseBack() {
                    @Override
                    public void onSuccess(Call call, String json) {
                        getV().hideLoadingDialog();
                        SimpleResult res = new Gson().fromJson(json, SimpleResult.class);
                        if(res != null) {
                            if (res.is_success == 1) {
                                getV().paySuccess();
                            } else {
                                getV().payFail();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        getV().hideLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                        getV().hideLoadingDialog();
                    }
                });
    }

    public void getMemberInfo() {
        HashMap<String, String> data = new HashMap<>();
        data.put("UID", UserHolder.getUID(getV()));
        data.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.MEMBERINDEX, data)
                .get()
                .execute(new BaseBack<MemberIndexRes>() {

                    @Override
                    public void onSuccess(Call call, MemberIndexRes res) {
                        if (res.code == 0 && res.data != null) {
                            getV().showGoodListView(res.data.member.level);
                        }
                    }
                });
    }
    private void toPayYiZhiFu(String payString){
        payString = payString.replace("{\"","").replace("\"}","")
                .replace("\":\"","=").replace("\",\"", "&");//.replace("+","%2B")
        PaymentTask paymentTask = new PaymentTask(getV());
        paymentTask.pay(payString, ConstantsUrl.YiZhiFuLicense);
    }
}
